package com.harmony.pilot.knowledge.service;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.harmony.pilot.knowledge.entity.BundleJson;
import com.harmony.pilot.knowledge.repository.BundleJsonRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * Bundle.json解析服务
 * 解析和分析OpenHarmony的bundle.json文件
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BundleJsonService {
    
    private final BundleJsonRepository bundleJsonRepository;
    private final Gson gson = new Gson();
    
    @Value("${openharmony.code.base-path:../ohcode}")
    private String codeBasePath;
    
    /**
     * 解析bundle.json文件
     */
    public BundleJson parseBundleJson(String filePath) {
        log.info("Parsing bundle.json: {}", filePath);
        
        try {
            Path path = Paths.get(filePath);
            String content = Files.readString(path);
            
            // 解析JSON
            JsonObject json = gson.fromJson(content, JsonObject.class);
            
            BundleJson bundle = new BundleJson();
            bundle.setFilePath(filePath);
            bundle.setContent(content);
            
            // 解析基本信息
            if (json.has("name")) {
                bundle.setName(json.get("name").getAsString());
            }
            
            if (json.has("description")) {
                bundle.setDescription(json.get("description").getAsString());
            }
            
            if (json.has("version")) {
                bundle.setVersion(json.get("version").getAsString());
            }
            
            if (json.has("license")) {
                bundle.setLicense(json.get("license").getAsString());
            }
            
            // 解析component信息
            if (json.has("component")) {
                JsonObject component = json.getAsJsonObject("component");
                
                if (component.has("name")) {
                    bundle.setComponentName(component.get("name").getAsString());
                }
                
                if (component.has("subsystem")) {
                    bundle.setSubsystem(component.get("subsystem").getAsString());
                }
                
                if (component.has("syscap")) {
                    JsonArray syscapArray = component.getAsJsonArray("syscap");
                    bundle.setSyscap(gson.toJson(syscapArray));
                }
                
                if (component.has("features")) {
                    JsonArray featuresArray = component.getAsJsonArray("features");
                    bundle.setFeatures(gson.toJson(featuresArray));
                }
                
                if (component.has("rom")) {
                    bundle.setRom(component.get("rom").getAsString());
                }
                
                if (component.has("ram")) {
                    bundle.setRam(component.get("ram").getAsString());
                }
                
                if (component.has("adapted_system_type")) {
                    JsonArray systemTypes = component.getAsJsonArray("adapted_system_type");
                    bundle.setAdaptedSystemType(gson.toJson(systemTypes));
                }
            }
            
            // 解析依赖
            if (json.has("deps")) {
                bundle.setDeps(gson.toJson(json.get("deps")));
            }
            
            return bundle;
            
        } catch (IOException e) {
            log.error("Failed to parse bundle.json: {}", filePath, e);
            return null;
        }
    }
    
    /**
     * 扫描并解析所有bundle.json文件
     */
    public List<BundleJson> scanAllBundleJson() {
        log.info("Scanning all bundle.json files...");
        
        List<BundleJson> bundles = new ArrayList<>();
        
        try {
            Path basePath = Paths.get(codeBasePath);
            Files.walk(basePath)
                    .filter(Files::isRegularFile)
                    .filter(path -> path.getFileName().toString().equals("bundle.json"))
                    .forEach(path -> {
                        BundleJson bundle = parseBundleJson(path.toString());
                        if (bundle != null) {
                            bundles.add(bundle);
                        }
                    });
            
            log.info("Found {} bundle.json files", bundles.size());
            
        } catch (IOException e) {
            log.error("Failed to scan bundle.json files", e);
        }
        
        return bundles;
    }
    
    /**
     * 保存或更新bundle.json
     */
    public BundleJson saveBundleJson(BundleJson bundle) {
        Optional<BundleJson> existing = bundleJsonRepository.findByFilePath(bundle.getFilePath());
        if (existing.isPresent()) {
            BundleJson existingBundle = existing.get();
            // 更新字段
            existingBundle.setName(bundle.getName());
            existingBundle.setDescription(bundle.getDescription());
            existingBundle.setVersion(bundle.getVersion());
            existingBundle.setSubsystem(bundle.getSubsystem());
            existingBundle.setComponentName(bundle.getComponentName());
            existingBundle.setSyscap(bundle.getSyscap());
            existingBundle.setFeatures(bundle.getFeatures());
            existingBundle.setDeps(bundle.getDeps());
            existingBundle.setContent(bundle.getContent());
            existingBundle.setRom(bundle.getRom());
            existingBundle.setRam(bundle.getRam());
            existingBundle.setAdaptedSystemType(bundle.getAdaptedSystemType());
            return bundleJsonRepository.save(existingBundle);
        } else {
            return bundleJsonRepository.save(bundle);
        }
    }
    
    /**
     * 根据子系统查询
     */
    public List<BundleJson> findBySubsystem(String subsystem) {
        return bundleJsonRepository.findBySubsystem(subsystem);
    }
    
    /**
     * 根据组件名称查询
     */
    public Optional<BundleJson> findByComponentName(String componentName) {
        return bundleJsonRepository.findByComponentName(componentName);
    }
}

